package com.jisheng.xb.web.access;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;


public class AccessVerifierFilter extends OncePerRequestFilter {



	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//忽略的URL  
        String[] ignoreUrl = new String[] {"/login.html"};  
        String url = request.getRequestURI();  
    	 boolean doFilter = chek(ignoreUrl,url);  
         if(doFilter){  
             Object obj = request.getSession().getAttribute("profile");  
             if(null==obj){  
                 // 如果session中不存在登录者实体，则弹出框提示重新登录  
                 PrintWriter out = response.getWriter();
                 String loginPage = request.getContextPath();
                 
                 if(url.indexOf("/wap/")!=-1){
                	 loginPage = loginPage+"/wap/login.html"; 
                 }else{
                	 loginPage = loginPage+"/login.html";
                 }
                 StringBuilder builder = new StringBuilder();  
                 builder.append("<script type=\"text/javascript\">");  
                 builder.append("window.top.location.href='");  
                 builder.append(loginPage);  
                 builder.append("';");  
                 builder.append("</script>");  
                 out.print(builder.toString());  
             }else {  
                 filterChain.doFilter(request, response);  
             }  
         }else{  
             filterChain.doFilter(request, response);  
         }  
       
    }  
      
    /** 
     * @param notFilter 不拦截的url 
     * @param url ：请求的url 
     * @return false：不拦截 
     * true：拦截 
     */  
    public boolean chek(String[] ignoreUrl,String url){  
    	//只拦截页面请求
        if(url.endsWith(".html")){  
            for (String s : ignoreUrl) {  
                if (url.indexOf(s) != -1) {  
                    return false;  
                }  
            }    
        }else{
        	return false;
        }
        
        return true;  
    }  

}
